package com.awesome.spring.netty.listener;

import com.awesome.spring.netty.handler.RedisChatServerHandler;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: u-social
 * @description: 队列消费信息
 * @author: Alex Wu
 * @createDate: 2025-03-17 16:02
 **/
@Component
public class RedisMessageSubscriber implements MessageListener {
    private static final Map<String, Channel> LOCAL_CHANNELS = new ConcurrentHashMap<>();

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String msg = new String(message.getBody(), StandardCharsets.UTF_8);
        String[] parts = msg.split(":");
        String targetServerId = parts[0];
        String targetUserId = parts[1];
        String chatMessage = parts[2];

        // 只有本机才处理
        if (RedisChatServerHandler.SERVER_ID.equals(targetServerId)) {
            Channel targetChannel = LOCAL_CHANNELS.get(targetUserId);
            if (targetChannel != null) {
                targetChannel.writeAndFlush(new TextWebSocketFrame(chatMessage));
            }
        }
    }
}
